package com.flute.haflute.alarm;

import static java.util.concurrent.TimeUnit.SECONDS;

import java.io.File;
import java.security.Security;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.flute.haflute.jobbox.common.CloudContext;
import com.flute.haflute.tools.PropertiesFileUtil;

public class MailService {
	String smtpHost = "mail.smtp.host";
	String mailAddress = "mail.12530.com";
	String mailMan = "xuzhoulin@12530.com";
	String mailManPass = "123456";
	String receiver = "xuzhoulin@12530.com";
	String character = "gb2312";
	String mailTitle = "分布式平台告警通知";
	boolean isSendAttachments = true;

	static String SEP = File.separator;
	private String messageContentMimeType = "text/html; charset=" + character;
	static String dir = CloudContext.getRootDir() + "bakfile";
	static String filename = "reportInfoBak.txt";
	static String fileDir = dir + SEP + filename;
	static MailService mailSvr;
	static String configFile = CloudContext.getRootDir()
			+ "conf/mail.properties";
	String contents;
	Properties properties = PropertiesFileUtil.loadPropertiesFile(configFile);

	long modifiytime = 0;

	final ScheduledExecutorService scheduler = Executors
			.newScheduledThreadPool(1);

	String osName = null;

	final Runnable checkFileTimeTask = new Runnable() {
		public void run() {
			File file = new File(configFile);
			long time = file.lastModified();
			if (modifiytime == 0) {
				modifiytime = time;
			} else if (modifiytime != time) {
				getConf();
			}
		}
	};

	MailService() {
		getConf();
		scheduler.scheduleAtFixedRate(checkFileTimeTask, 30, 1 * 60 * 60,
				SECONDS);
		osName = System.getProperty("os.name").toLowerCase();
		// if (osName.contains("windows")) {
		// SEP = "\\";
		// } else {
		// SEP = "/";
		// }
	}

	public void getConf() {
		smtpHost = PropertiesFileUtil.getProperty(properties, "smtpHost",
				smtpHost);
		mailAddress = PropertiesFileUtil.getProperty(properties, "mailAddress",
				mailAddress);
		mailMan = PropertiesFileUtil
				.getProperty(properties, "mailMan", mailMan);
		mailManPass = PropertiesFileUtil.getProperty(properties, "mailManPass",
				mailManPass);
		receiver = PropertiesFileUtil.getProperty(properties, "receiver",
				receiver);
		// mailTitle = PropertiesFileUtil.getProperty(properties, "mailTitle",
		// mailTitle);
		// try {
		// mailTitle = new String(mailTitle.getBytes("ISO8859-1"), "utf-8");
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }
		character = PropertiesFileUtil.getProperty(properties, "character",
				character);
		String isSendAttachments = PropertiesFileUtil.getProperty(properties,
				"isSendAttachments", "0");
		if (isSendAttachments.equals("1"))
			this.isSendAttachments = false;
	}

	public static MailService getInstance() {

		if (mailSvr == null) {
			mailSvr = new MailService();
		}
		return mailSvr;
	}

	public Properties getProperties() {
		Properties props = System.getProperties();
		props.setProperty(smtpHost, mailAddress);
		props.put("mail.smtp.auth", "true");
		return props;
	}

	public void sendMail(String content) throws AddressException,
			MessagingException {
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		// Transport 是用来发送信息的
		Transport
				.send(buildMimeMessage(mailMan, mailManPass, receiver, content));
	}

	public Message buildMimeMessage(final String username,
			final String password, String receiver, String content)
			throws AddressException, MessagingException {
		Session session = Session.getDefaultInstance(getProperties(),
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		Message msg = new MimeMessage(session);

		// 鉴别发送者，您可以使用setFrom()和setReplyTo()方法。
		msg.addFrom(InternetAddress.parse("[发件人]"));// 地址来源,没作用?
		msg.setReplyTo(InternetAddress.parse("[回复时收件人]"));// 回复时用的地址
		// 消息接收者
		if (receiver.indexOf(",") != -1) {
			String[] receivers = receiver.split(",");
			for (String rev : receivers) {
				msg.addRecipients(Message.RecipientType.TO,
						InternetAddress.parse(rev, false));
			}
		} else {
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(receiver, false));

		}

		msg.setSubject(mailTitle);
		msg.setSentDate(new Date());

		// 邮件内容数据（Content）
		msg.setContent(buildMimeMultipart(content, new Vector<String>() {
			private static final long serialVersionUID = 1L;
			{
				add(fileDir);
			}
		}));

		return msg;
	}

	public Multipart buildMimeMultipart(String msgContent,
			Vector<String> attachedFileList) throws MessagingException {
		Multipart mPart = new MimeMultipart();

		// 邮件正文
		MimeBodyPart mBodyContent = new MimeBodyPart();// MIME邮件段体
		if (msgContent != null) {
			mBodyContent.setContent(msgContent, messageContentMimeType);
		} else {
			mBodyContent.setContent("", messageContentMimeType);
		}
		mPart.addBodyPart(mBodyContent);

		// 附件
		String file;
		if (attachedFileList != null && isSendAttachments) {
			for (Enumeration<String> fileList = attachedFileList.elements(); fileList
					.hasMoreElements();) {
				file = (String) fileList.nextElement();
				MimeBodyPart mBodyPart = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(file);
				mBodyPart.setDataHandler(new DataHandler(fds));
				mBodyPart.setFileName(filename);
				mPart.addBodyPart(mBodyPart);
			}
		}
		return mPart;
	}

}
